/*
 * Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
 * 作者:张谦
 */

import React, {useCallback} from 'react';
import {DatePicker, Form, Input, Modal, Radio, Space, Spin, Switch} from 'antd';
import {SysUserModel} from '../data';
import moment from "moment";
import DeptTreeSelect from "@/pages/sys/dept/components/DeptTreeSelect";
import {isAdminUser} from "@/utils/utils";
import DicTreeSelect from "@/components/Dic/DicSelectTree";
import {FormInstance} from "antd/lib/form";
import {EditDialogProps} from "@/global";
import styles from "@/utils/utils.less";
import EditModalFooter from "@/lib/EditModalFooter";
import useForm from "@/hooks/useForm";
import useLoad from "@/hooks/useLoad";
import service from "@/pages/sys/user/service";
import useEditModalFooter from "@/hooks/useEditModalFooter";
import useSave from "@/hooks/useSave";
import {Store} from "rc-field-form/lib/interface";
import RoleSelect from "@/components/sys/RoleSelect";

const FormItem = Form.Item;
const {RangePicker} = DatePicker;

/** 表单布局 */
const formLayout = {
  labelCol: {span: 7},
  wrapperCol: {span: 13},
};

/** 系统用户编辑表单组件 */
const Edit: React.FC<EditDialogProps> = props => {
  const {
    params: {
      created, newModel = {
        category: 0,
        status: true,
        pwdMustModify: 0,
        pwdAllowModify: 0,
        visible: 1,
        admin: false,
        pwdNeverExpire: 0
      }, id, onSubmitSucess
    }, visible, hide
  } = props;
  const {form, bind, reset, submit} = useForm();
  let {loading: dataLoading, data: model} = useLoad<SysUserModel>({
    isLoad: Boolean(id),
    isClear: false,
    defaultData: newModel,
    onLoad: () => service.selectById(id),
    onSuccess: optionsData,
  }, [id]);
  const {finishCallback, ...footerProps} = useEditModalFooter({created, reset, hide, onSubmitSucess});
  const {submitLoading, save} = useSave<SysUserModel>({created, onSave: service.save,});

  const onFinish = useCallback((values: any) => {
    dataProcessing(values);
    save(model, values, finishCallback);
  }, [model]);
  //
  // //新建时数据初始化
  // useMount(() => {
  //   created && bind({
  //     category: 0,
  //     status: true,
  //     pwdMustModify: 0,
  //     pwdAllowModify: 0,
  //     visible: 1,
  //     admin: false,
  //     pwdNeverExpire: 0
  //   });
  // })

  //加载选项
  function optionsData(data: SysUserModel | undefined) {
    if (!data || created) return;

    data.allowTime = [];
    if (data.allowStartTime) {
      data.allowTime[0] = moment(data.allowStartTime);
    }
    if (data.allowEndTime) {
      data.allowTime[1] = moment(data.allowEndTime);
    }
    bind(data);
  }

  function dataProcessing(values: any) {
    if (values.allowTime != undefined && values.allowTime.length > 0) {
      if (values.allowTime.length > 1) {
        values.allowStartTime = values.allowTime[0];
        values.allowEndTime = values.allowTime[1];
      } else {
        values.allowStartTime = values.allowTime[0];
      }
    }
  }

  return (
    <Modal
      title={created ? '新建系统用户' : '编辑系统用户'}
      visible={visible}
      width={600}
      destroyOnClose
      maskClosable={false}
      onCancel={hide}
      footer={(
        <EditModalFooter
          {...footerProps}
          okLoading={dataLoading || submitLoading}
          onOk={submit}
          onCancel={hide}/>
      )}
    >
      <Spin spinning={dataLoading || submitLoading} wrapperClassName={styles.h100p}>
        {model && (<EditForm {...{form, model, created, onFinish}}/>)}
      </Spin>
    </Modal>
  );
};

/** 表单组件  */
function EditForm(props: { created: boolean, model: SysUserModel, form: FormInstance, onFinish: (values: Store) => void }) {
  const {created, model, form, onFinish} = props;
  return (
    <Form form={form} onFinish={onFinish} initialValues={model} {...formLayout}>
      <FormItem
        name="account"
        label="账号"
        rules={[{required: true, message: '请输入账号'}]}
      >
        <Input maxLength={100}/>
      </FormItem>
      <FormItem
        name="name"
        label="姓名"
        rules={[{required: true, message: '请输入姓名'}]}
      >
        <Input maxLength={20}/>
      </FormItem>
      {created && (<>
        <FormItem
          name="pwd"
          label="密码"
          rules={[{required: true, message: '请输入密码'}]}
        >
          <Input.Password maxLength={100}/>
        </FormItem>
        <FormItem
          name="pwd2"
          label="确认密码"
          dependencies={['pwd']}
          rules={[
            {required: true, message: '请输入密码'},
            ({getFieldValue}) => ({
              validator(rule, value) {
                if (!value || getFieldValue('pwd') === value) {
                  return Promise.resolve();
                }
                return Promise.reject('确认密码必须与密码输入一致!');
              },
            }),
          ]
          }
        >
          <Input.Password maxLength={500}/>
        </FormItem>
      </>)}
      <FormItem
        name="deptId"
        label="机构"
        rules={[{required: true, message: '请选择机构！'}]}
      >
        <DeptTreeSelect deptId={model.deptId || ''}/>
      </FormItem>
      <FormItem
        name="post"
        label="职位"
      >
        <DicTreeSelect dicCode={"sys.user.post"}/>
      </FormItem>
      <FormItem
        name="roleIds"
        label="角色"
      >
        <RoleSelect
          placeholder="请选择角色"
          getPopupContainer={triggerNode => triggerNode.parentElement}
        />
      </FormItem>
      <FormItem
        name="category"
        label="账号类型"
      >
        <Radio.Group>
          <Radio value={0}>系统账号</Radio>
          <Radio value={1}>企业账号</Radio>
        </Radio.Group>
      </FormItem>
      <FormItem
        name="mobile"
        label="手机号码"
      >
        <Input maxLength={50}/>
      </FormItem>
      <FormItem
        name="email"
        label="电子邮件"
      >
        <Input maxLength={100}/>
      </FormItem>
      <Form.Item name="allowTime" label="开始有效期-结束有效期">
        <RangePicker style={{width: '100%'}}/>
      </Form.Item>
      <FormItem label="选项">
        <Space direction="horizontal">
          <FormItem noStyle name="status" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用"/></FormItem>
          <FormItem noStyle name="pwdAllowModify" valuePropName="checked"><Switch checkedChildren="允许用户更改密码"
                                                                                  unCheckedChildren="不允许用户更改密码"/></FormItem>
        </Space>
        <Space direction="horizontal">
          <FormItem noStyle name="pwdNeverExpire" valuePropName="checked"><Switch checkedChildren="密码永不过期"
                                                                                  unCheckedChildren="密码会过期"/></FormItem>
          <FormItem noStyle name="pwdMustModify" valuePropName="checked"><Switch checkedChildren="下次登录时须更改密码"
                                                                                 unCheckedChildren="下次登录时不用更改密码"/></FormItem>
        </Space>
        {isAdminUser() && (<Space direction="horizontal">
          <FormItem noStyle name="visible" valuePropName="checked"><Switch checkedChildren="显示"
                                                                           unCheckedChildren="不显示"/></FormItem>
          <FormItem noStyle name="admin" valuePropName="checked"><Switch checkedChildren="管理员"
                                                                         unCheckedChildren="普通用户"/></FormItem>
        </Space>)}
      </FormItem>
      <FormItem
        name="remark"
        label="备注"
      >
        <Input.TextArea maxLength={500}/>
      </FormItem>
    </Form>
  );
}

export default React.memo(Edit);

